package gw.com.android.ui.chart.views;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.PorterDuff;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gwtsz.chart.output.utils.ChartConfig;
import com.gwtsz.chart.output.utils.GTTKDataModel;
import com.gwtsz.chart.output.utils.Periodicity;
import com.gwtsz.gts2.hx.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.DataManager;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.model.DataItemDetail;
import www.com.library.util.DoubleConverter;
import www.com.library.util.ProductPrecision;
import www.com.library.util.StringFormatter;
import www.com.library.util.StringUtils;

/**
 * 图片界面顶部报价自定义控件
 *
 * @author reeta
 */
public class ChartPriceBar extends RelativeLayout {

    @BindView(R.id.chart_price_bar_root)
    View mRootView;
    @Nullable
    @BindView(R.id.range_above)
    ImageView mRangeAbove;
    @Nullable
    @BindView(R.id.range_below)
    ImageView mRangeBelow;
    @BindView(R.id.price_new)
    TextView mNewPriceView; // 现价
    @BindView(R.id.price_time)
    TextView mTimeView; // 时间
    @BindView(R.id.price_range)
    TextView mRangeView; // 涨跌
    @BindView(R.id.price_precent)
    TextView mPrecentView; // 幅度
    @BindView(R.id.price_open)
    TextView mOpenView; // 开盘价
    @BindView(R.id.price_high)
    TextView mHighView; // 高价
    @BindView(R.id.price_close)
    TextView mCloseView; // 昨收价
    @BindView(R.id.price_low)
    TextView mLowView; // 低价
    @Nullable
    @BindView(R.id.layout_range)
    LinearLayout mRangeLayout;//涨跌幅背景
    @Nullable
    @BindView(R.id.product_name)
    TextView mProNameView; // 产品名
    @Nullable
    @BindView(R.id.product_sub_name)
    TextView mProSubNameView; // 英文名

    private DataItemDetail mTickModel;
    public boolean isCursor = false;
    private int mScreenOrientation = Configuration.ORIENTATION_PORTRAIT;

    public ChartPriceBar(Context context) {
        super(context);
        initView(context);
    }

    public ChartPriceBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);
    }

    public ChartPriceBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public void initView(Context act) {
        View mView = LayoutInflater.from(act).inflate(R.layout.chart_price_bar, this, true);
        ButterKnife.bind(this, mView);
        mScreenOrientation = ChartConfig.instance().mScreenOrientation;
        if (null != mRangeLayout) {
            mRangeLayout.setBackgroundResource(getBackgroundId(ColorThemeUtil.instance().isGreenRise));
        }
    }


    /**
     * 根据涨跌颜色设置背景（取涨方向）
     *
     * @param isGreenRise
     * @return
     */
    private int getBackgroundId(boolean isGreenRise) {
        int bgId;
        if (isGreenRise) {
            bgId = R.drawable.chart_uptitle_background;
        } else {
            bgId = R.drawable.chart_uptitile_background_switch;
        }

        return bgId;
    }

    /**
     * 设置界面数据
     *
     * @param model
     */
    public void setTickData(DataItemDetail model) {
        if (model == null) {
            return;
        }

        mTickModel = model;
        if (null != mProNameView) {
            mProNameView.setText(DataManager.instance().getPrdName(mTickModel));
        }
        if (null != mProSubNameView) {
            mProSubNameView.setText(mTickModel.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME));
        }

        mNewPriceView.setText(model.getString(GTSConst.JSON_KEY_CURPRICE));
        ColorThemeUtil.instance().setNewPriceColor(mNewPriceView, model.getInt(GTSConst.JSON_KEY_CURPRICESTATE), model.getInt(GTSConst.JSON_KEY_CURPRICEARRAW), true);
        if (isCursor) {
            return;
        }
        int statu = AppContances.PRICE_UNCHANGE;
        if (mTickModel.getString(GTSConst.JSON_KEY_RISE).startsWith("-")) {
            statu = AppContances.PRICE_DECREASE;
        } else if (mTickModel.getString(GTSConst.JSON_KEY_RISE).startsWith("+")) {
            statu = AppContances.PRICE_INCREASE;
        }
        mRangeView.setText(mTickModel.getString(GTSConst.JSON_KEY_RISE));
        if (mScreenOrientation != Configuration.ORIENTATION_PORTRAIT) {
            ColorThemeUtil.instance().setPriceColor(mRangeView, statu);
        }

        statu = AppContances.PRICE_UNCHANGE;
        if (mTickModel.getString(GTSConst.JSON_KEY_PERCENT).startsWith("-")) {
            statu = AppContances.PRICE_DECREASE;
        } else if (mTickModel.getString(GTSConst.JSON_KEY_PERCENT).startsWith("+")) {
            statu = AppContances.PRICE_INCREASE;
        }
        mPrecentView.setText(mTickModel.getString(GTSConst.JSON_KEY_PERCENT) + "%");
        if (mScreenOrientation != Configuration.ORIENTATION_PORTRAIT) {
            ColorThemeUtil.instance().setPriceColor(mPrecentView, statu);
        }

        setPriceView();
    }

    /**
     * 设置界面其他价格
     */
    private void setPriceView() {
        mTimeView.setText(StringFormatter.instance().secToTime(mTickModel.getInt(GTSConst.JSON_KEY_TIME)));

        String mTitle = "";
        String mPriceStr = "";
        SpannableString mPriceSs = null;
        // 开盘价
        mTitle = AppMain.getAppString(R.string.chart_price_open);
        mPriceStr = mTitle + mTickModel.getString(GTSConst.JSON_KEY_OPENPRICE);
        mPriceSs = new SpannableString(mPriceStr);
        mPriceSs.setSpan(new ForegroundColorSpan(ColorThemeUtil.instance().color_c), 0, mTitle.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mPriceSs.setSpan(new ForegroundColorSpan(ColorThemeUtil.instance().getPriceColor(mTickModel.getInt(GTSConst.JSON_KEY_OPENPRICESTATE))), mTitle.length(), mPriceStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mOpenView.setText(mPriceSs);

        // 收盘价
        mTitle = AppMain.getAppString(R.string.chart_price_close);
        mPriceStr = mTitle + mTickModel.getString(GTSConst.JSON_KEY_CURPRICE);
        mPriceSs = new SpannableString(mPriceStr);
        float curPrice = DoubleConverter.toFloatData(mTickModel.getString(GTSConst.JSON_KEY_CURPRICE));
        float closePrice = DoubleConverter.toFloatData(mTickModel.getString(GTSConst.JSON_KEY_CLOSEPRICE));
        int statu = AppContances.PRICE_UNCHANGE;
        if (closePrice > 0) {
            if (curPrice > closePrice) {
                statu = AppContances.PRICE_INCREASE;
            } else if (curPrice < closePrice) {
                statu = AppContances.PRICE_DECREASE;
            }
        }
        mPriceSs.setSpan(new ForegroundColorSpan(ColorThemeUtil.instance().color_c), 0, mTitle.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mPriceSs.setSpan(new ForegroundColorSpan(ColorThemeUtil.instance().getPriceColor(statu)), mTitle.length(), mPriceStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mCloseView.setText(mPriceSs);

        // 最高价
        mTitle = AppMain.getAppString(R.string.chart_price_high);
        mPriceStr = mTitle + mTickModel.getString(GTSConst.JSON_KEY_HIGHPRICE);
        mPriceSs = new SpannableString(mPriceStr);
        mPriceSs.setSpan(new ForegroundColorSpan(ColorThemeUtil.instance().color_c), 0, mTitle.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mPriceSs.setSpan(new ForegroundColorSpan(ColorThemeUtil.instance().getPriceColor(mTickModel.getInt(GTSConst.JSON_KEY_HIGHPRICESTATE))), mTitle.length(), mPriceStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mHighView.setText(mPriceSs);

        // 最低价
        mTitle = AppMain.getAppString(R.string.chart_price_low);
        mPriceStr = mTitle + mTickModel.getString(GTSConst.JSON_KEY_LOWPRICE);
        mPriceSs = new SpannableString(mPriceStr);
        mPriceSs.setSpan(new ForegroundColorSpan(ColorThemeUtil.instance().color_c), 0, mTitle.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mPriceSs.setSpan(new ForegroundColorSpan(ColorThemeUtil.instance().getPriceColor(mTickModel.getInt(GTSConst.JSON_KEY_LOWPRICESTATE))), mTitle.length(), mPriceStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mLowView.setText(mPriceSs);
    }

    /**
     * 设置光标数据
     *
     * @param closePrice
     * @param dataModel
     */
    public void setCursorData(double closePrice, GTTKDataModel dataModel, ProductPrecision mPrecision) {
        if (null == dataModel) {
            mTimeView.setText(StringUtils.NA_MSG);
            mOpenView.setText(StringUtils.NA_MSG);
            mCloseView.setText(StringUtils.NA_MSG);
            mHighView.setText(StringUtils.NA_MSG);
            mLowView.setText(StringUtils.NA_MSG);
            mPrecentView.setText(StringUtils.NA_MSG);
            mRangeView.setText(StringUtils.NA_MSG);
            return;
        }

        //设置当前时间
        Periodicity period = ChartConfig.instance().getChartPeriodicity();
        //日线，周线，月线显示日期，其他显示时分秒
        if (period.nativeKLineType() != Periodicity.K_LINE_TYPE_DAY && period.nativeKLineType() != Periodicity.K_LINE_TYPE_WEEK && period.nativeKLineType() != Periodicity.K_LINE_TYPE_MONTH) {
            mTimeView.setText(StringFormatter.instance().secToTime(dataModel.priceTime));
        } else {
            mTimeView.setText("");
        }

        String mChange = mPrecision.format(dataModel.changePrice);
        //设置涨幅
        if (dataModel.changePrice > 0) {
            mChange = "+" + mChange;
        }
        mRangeView.setText(mChange);
        setTextColor(dataModel.changePrice, mRangeView);

        String mRange = DoubleConverter.to2Decimal(dataModel.range);
        //设置涨跌
        if (mRange.equals("0.00") || mRange.equals("-0.00")) {
            mRange = "0.00";
            mPrecentView.setText(mRange + "%");
        } else if (Double.parseDouble(mRange) > 0) {
            mPrecentView.setText("+" + mRange + "%");
        } else {
            mPrecentView.setText(mRange + "%");
        }
        setTextColor(dataModel.range, mPrecentView);

        //开盘价
        setTextColor(closePrice, dataModel.openPrice, AppMain.getAppString(R.string.chart_price_open), mOpenView, mPrecision);

        //收盘价
        setTextColor(closePrice, dataModel.lastPrice, AppMain.getAppString(R.string.chart_price_close), mCloseView, mPrecision);

        //最高价
        setTextColor(closePrice, dataModel.highPrice, AppMain.getAppString(R.string.chart_price_high), mHighView, mPrecision);

        //最低价
        setTextColor(closePrice, dataModel.lowPrice, AppMain.getAppString(R.string.chart_price_low), mLowView, mPrecision);
    }

    /**
     * 设置颜色
     *
     * @param price
     * @param view
     */
    private void setTextColor(double price, TextView view) {
        if (mScreenOrientation == Configuration.ORIENTATION_PORTRAIT) {
            view.setTextColor(ColorThemeUtil.instance().color_e);
        } else {
            view.setTextColor(ColorThemeUtil.instance().IdleColor);
            //设置幅度
            if (price > 0) {
                view.setTextColor(ColorThemeUtil.instance().RiseColor);
            } else if (price < 0) {
                view.setTextColor(ColorThemeUtil.instance().FallColor);
            }
        }
    }

    /**
     * 设置价格和颜色
     *
     * @param closePrice
     * @param price
     * @param view
     * @param mPrecision
     */
    private void setTextColor(double closePrice, double price, String title, TextView view, ProductPrecision mPrecision) {
        int statu = AppContances.PRICE_UNCHANGE;
        if (closePrice > 0) {
            if (price > closePrice) {
                statu = AppContances.PRICE_INCREASE;
            } else if (price < closePrice) {
                statu = AppContances.PRICE_DECREASE;
            }
        }
        String mPriceStr = title + mPrecision.format(price);
        SpannableString mPriceSs = new SpannableString(mPriceStr);
        mPriceSs.setSpan(new ForegroundColorSpan(ColorThemeUtil.instance().color_c), 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mPriceSs.setSpan(new ForegroundColorSpan(ColorThemeUtil.instance().getPriceColor(statu)), title.length(), mPriceStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        view.setText(mPriceSs);
    }

    public void onNightMode(boolean isNight) {
        if (isNight) {
            mRootView.setBackgroundColor(getResources().getColor(R.color.color_night_bg));
            if (mRangeAbove != null) {
                mRangeAbove.setColorFilter(0xFF323744, PorterDuff.Mode.SRC_ATOP);
            }
            if (mRangeBelow != null) {
                mRangeBelow.setColorFilter(0xFF323744, PorterDuff.Mode.SRC_ATOP);
            }
            if (mProNameView != null) {
                mProNameView.setTextColor(getResources().getColor(R.color.color_f));
            }
            mTimeView.setTextColor(getResources().getColor(R.color.color_night_text));
        } else {
            mRootView.setBackgroundColor(getResources().getColor(R.color.color_f));
            if (mRangeAbove != null) {
                mRangeAbove.clearColorFilter();
            }
            if (mRangeBelow != null) {
                mRangeBelow.clearColorFilter();
            }
            if (mProNameView != null) {
                mProNameView.setTextColor(getResources().getColor(R.color.color_b));
            }
            mTimeView.setTextColor(getResources().getColor(R.color.color_h));
        }
    }

}
